package com.swq.java.code.chapter20.code15;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;

public class LoveBox extends JPanel implements Runnable {
    private int index = 0;    //图片的索引
    private Thread changer;    //动态改变图片的线程，形成动画效果
    private boolean stopFlag = true;  //控制线程启动与关闭的标志
    private Image[] images; //存放献爱心图片
    private JButton contrlButton = new JButton("  开始献爱心！ ");
    private URL getResource(String name) {
        return getClass().getClassLoader().getResource(name);
    }
    public LoveBox() {

        images = new Image[5];
        //加载图片
        Toolkit tk = getToolkit();
        //  2019/4/29 直接获取resource里面的资源
        images[0] = tk.getImage(getResource("donate0.jpg"));
        images[1] = tk.getImage(getResource("donate1.jpg"));
        images[2] = tk.getImage(getResource("donate2.jpg"));
        images[3] = tk.getImage(getResource("donate3.jpg"));
        images[4] = tk.getImage(getResource("donate4.jpg"));

        contrlButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (stopFlag) start();
                else stop();
            }
        });

        setBackground(Color.WHITE);
        setLayout(new BorderLayout());
        add(contrlButton, BorderLayout.NORTH);
    }

    public void start() {
        changer = new Thread(this);
        stopFlag = false;
        index = 1;
        contrlButton.setText("  献爱心活动结束！ ");
        changer.start();
    }

    public void paint(Graphics g) {
        super.paint(g);
        if (index > -1 && index < 5) {
            g.drawImage(images[index], 20, 40, this);
            g.drawString("爱洒人间，大爱无疆", 90, 250);
        }
    }

    public void stop() {
        stopFlag = true;
        contrlButton.setText("  开始献爱心！ ");
    }

    public void run() {
        while (!stopFlag) {
            repaint();
            try {
                if (index == 0 || index == 4) Thread.sleep(350);
                else Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            if (++index > 4) index = 0;   //显示下一张照片
        }

        index = 0;
        repaint();  //刷新图形
    }

    public static void main(String args[]) {
        JFrame gui = new JFrame("献爱心箱");
        LoveBox loveBox = new LoveBox();

        gui.setContentPane(loveBox);
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(300, 300);
        gui.setVisible(true);
    }
}